package landun.dao.impl;

import landun.dao.BaseDao;
import landun.dao.EmpDao;
import landun.pojo.SysEmployee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository("empDao")
public class EmpDaoImpl extends BaseDao<SysEmployee> implements EmpDao {
    @Autowired
    public EmpDaoImpl(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    public SysEmployee findByName(final String name) {
        return (SysEmployee)this.getHibernateTemplate().execute(new HibernateCallback<Object>() {
            @Override
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("from SysEmployee where sn = ?").setParameter(0,name).uniqueResult();
            }
        });
    }

    @Override
    public SysEmployee findByPosition(final Integer positionId,final Integer deptId) {
        return getHibernateTemplate().execute(new HibernateCallback<SysEmployee>() {
            @Override
            public SysEmployee doInHibernate(Session session) throws HibernateException, SQLException {
                List<Object> objects = new ArrayList<>();
                String hql = "from SysEmployee where position.id=? ";
                objects.add(positionId);
                if(positionId==2){
                    hql+=" and departmentId=? ";
                    objects.add(deptId);
                }
                Query query = session.createQuery(hql);
                for (int i = 0; i <objects.size() ; i++) {
                    query.setParameter(i,objects.get(i));
                }
                return (SysEmployee)query.setFirstResult(0).setMaxResults(1).uniqueResult();
            }
        });
    }

    @Override
    public void save(SysEmployee sysEmployee) {
        this.getHibernateTemplate().saveOrUpdate(sysEmployee);
    }

    @Override
    public void delete(SysEmployee sysEmployee) {
        this.getHibernateTemplate().delete(sysEmployee);
    }

//    @Override
    public SysEmployee load(Serializable id) {
        return (SysEmployee)this.getHibernateTemplate().load(SysEmployee.class,id);
    }

//    @Override
    public SysEmployee get(Serializable id) {
        return (SysEmployee)this.getHibernateTemplate().get(SysEmployee.class,id);
//                find("from SysEmployee where id = ?",id);
    }


}
